package com.bestcem.xm.deliver.config;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadFactory;

/**
 * @ClassName: XmCustomerThreadFactory
 * @Description: 兜底异常处理，如果没写try catch处理，这里会兜底
 * @Author: chenglong.yue
 * @Date: 2022/11/29 11:15
 */
@Slf4j
@Component
public class XmCustomThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(@NotNull Runnable r) {
        Thread thread = new Thread(r);
        thread.setUncaughtExceptionHandler((t, e) -> {
            String result = generateErrorMessage(e);
            log.error(result);
        });
        return thread;
    }

    private String generateErrorMessage(Throwable e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        StringBuilder result = new StringBuilder(e + "\n");
        for (int index = stackTraceElements.length - 1; index >= 0; --index) {
            result.append("at [").append(stackTraceElements[index].getClassName()).append(",");
            result.append(stackTraceElements[index].getFileName()).append(",");
            result.append(stackTraceElements[index].getMethodName()).append(",");
            result.append(stackTraceElements[index].getLineNumber()).append("]\n");
        }
        return result.toString();
    }

}
